package ecom.beans.dao;

import ecom.beans.AccountBean;
import ecom.beans.exception.AccountBeanException;
import ecom.beans.exception.DAONotUniqueException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AccountDAO extends DAO {

    public static void saveAccount(AccountBean account) throws AccountBeanException, DAONotUniqueException {
        if (getByIBAN(account.getIban()) == null) {
            if (account.getIban().length() > 34 || account.getIban().length() < 34) {
                throw new AccountBeanException("IBAN must contain 34 characters");
            }
            saveOrUpdate(account);
        } else {
            throw new DAONotUniqueException("This account already exist");
        }
    }

    public static void deleteAccount(AccountBean account) {
        delete(account);
    }

    public static void deleteAccount(String iban) throws AccountBeanException, DAONotUniqueException {
        AccountBean account = getByIBAN(iban);
        if (account != null) {
            delete(account);
        } else {
            throw new DAONotUniqueException("This account already exist");
        }
    }

    public static void updateAccount(AccountBean account) {
        saveOrUpdate(account);
    }

    public static Set getAllAccounts(String order) {
        return fetchAll("AccountBean.findAll", null, order);
    }

    public static AccountBean getByIBAN(String iban) {
        List parameters = new ArrayList();
        parameters.add("iban");
        parameters.add(iban);
        return (AccountBean) fetchOne("AccountBean.findByIban", parameters);
    }
}
